package org.lion.action;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ModelDriven;
import org.apache.struts2.ServletActionContext;
import org.lion.bean.LoginInfo;
import org.lion.proxy.input.student.LoginInput;
import org.lion.proxy.output.student.StudentLoginResponse;
import org.lion.service.Client;
import org.lion.utils.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import retrofit2.Response;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * Created by lion on 3/7/17.
 */
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class LoginAction extends BaseAction implements ModelDriven<LoginInput> {

    @Autowired
    Client client;

    @Autowired
    LoginInfo loginInfo;

    @Autowired
    private LoginInput model;


    @Override
    public LoginInput getModel() {
        return model;
    }

    public String student() throws IOException {
        Map map = model.toMap();
        Response response = client.studentLogin(map).execute();
        StudentLoginResponse studentLoginResponse = (StudentLoginResponse) response.body();
        if (studentLoginResponse.getRetcode() != 0) {
            JsonUtil.ajaxResult(ServletActionContext.getResponse(), 1, "login failed :" + studentLoginResponse.getMsg());
        } else {
            List<String> list = response.headers().toMultimap().get("set-cookie");
            loginInfo.store(list);
            loginInfo.setResponse(studentLoginResponse);

            Map<String, Object> session = ServletActionContext.getContext().getSession();
            session.put("userInfo", loginInfo);
            Gson gson = new Gson();
            JsonUtil.write_json(ServletActionContext.getResponse(), gson.toJson(studentLoginResponse));
        }
        return NONE;
    }


}
